/**
* <p>Title: TestImplCommandLineRunner.java</p>
* <p>Copyright: Copyright (c) 2017</p>
* <p>Company: lty</p>
*/
package com.lantaiyuan.ebus.task;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lantaiyuan.ebus.model.PushPlatformGroup;

/**
 * <p>Title: TestImplCommandLineRunner</p>
 * <p>Description: RESTful调用第三方接口</p>
 * <p>Company: lty</p>
 * @author liuhao
 * @date 2017年5月15日 下午3:57:36
 */
@Component
public class RestTask {
	private static final Logger logger = LoggerFactory.getLogger(RestTask.class);
	
	@Autowired
	private RestTemplate restTemplate;

	@Value("${push.url}")
	private String pushUrl;
	
	//缓存60s
	//<String, JSONArray>表示缓存的数据结构，类似Map
	private LoadingCache<String, JSONArray> cache = CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS)
			.build(new CacheLoader<String, JSONArray>() {
				@Override
				public JSONArray load(String key) throws Exception {
					//return new RestTemplate().getForEntity("http://127.0.0.1:8080/ebus-app-global/custom/push", JSONArray.class).getBody();
					return restTemplate.getForEntity(pushUrl, JSONArray.class).getBody();
				}
			});

	/*********** HTTP GET method *************/
	public List<PushPlatformGroup> invokeUrl() {
		JSONArray jsonArray = null;
		
		try {
			//key名称可任意指定
			jsonArray = cache.get("push");
		} catch (Exception e) {
			logger.error("推送url接口异常！", e);
			return null;
		}

		if (jsonArray == null) {
			return null;
		}

		return JSONObject.parseArray(jsonArray.toJSONString(), PushPlatformGroup.class);
	}

//	public static void main(String[] args) throws ExecutionException, InterruptedException {
        //为便于测试，上面超时时间改为5
//		RestTask restUtil = new RestTask();
//		for(int i = 0 ;i<21 ;i++){
//			TimeUnit.SECONDS.sleep(1);
//			//key名称可任意指定
//			System.err.println(restUtil.cache.get("push"));
//		}
//	}
}
